import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form, Transfer } from 'antd';

@Form.create()
@connect(state => ({
  allAttr: state.attribute.list,
  attrLoading: state.attribute.loading,
}))
export default class AttrSelectTransfer extends PureComponent {
  state = {
    sourceKeys: [],
    targetKeys: [],
    selectedKeys: [],
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'attribute/fetch',
    });
  }

  componentWillReceiveProps(nextProps) {
    if (!nextProps.attrLoading && nextProps.allAttr.length > 0) {
      const attrList = nextProps.allAttr;
      const sourceKeys = attrList.map((attr, index) => {
        return {
          key: index,
          id: attr.id,
          title: attr.attr_name,
          description: attr.attr_desc,
        };
      });
      this.setState({
        sourceKeys,
      });
    }
  }

  updateChange = (nextTargetKeys) => {
    this.setState({ targetKeys: nextTargetKeys });
    const { validateFields } = this.props.form;
    validateFields((err) => {
      if (!err && typeof this.props.handleChange === 'function') {
        const selectAttrs = this.props.allAttr.reduce((acc, attr, index) => {
          if (nextTargetKeys.indexOf(index) > -1) {
            acc.push(attr);
          }
          return acc;
        }, []);
        this.props.handleChange(selectAttrs);
      }
    });
  }

  handleSelectChange = (sourceSelectedKeys, targetSelectedKeys) => {
    this.setState({ selectedKeys: [...sourceSelectedKeys, ...targetSelectedKeys] });
  }

  render() {
    const state = { ...this.state };
    const { getFieldDecorator } = this.props.form;

    return (
      <Form.Item>
        {getFieldDecorator('type_attr', {
          rules: [
            { type: 'array', required: true, min: 3, message: '至少配置3个属性' },
          ],
        })(
          <Transfer
            style={{ marginBottom: 16 }}
            showSearch
            listStyle={{
              width: 220,
              height: 500,
            }}
            dataSource={this.state.sourceKeys}
            titles={['源属性', '已添加']}
            targetKeys={state.targetKeys}
            selectedKeys={state.selectedKeys}
            onSelectChange={this.handleSelectChange}
            onChange={this.updateChange}
            render={item => item.title}
          />
          )}
      </Form.Item>
    );
  }
}
